//Twitter + Google Map V3 API Geocode
//StackOverflow Question: http://stackoverflow.com/questions/5489225/struggling-with-google-maps-geocoding-api/5490739#5490739
var team1 = 'afc';
var team2 = 'lfc';
//var userLocation1 = 'manchester';
//var userLocation2 = 'london';
var url1 = "http://search.twitter.com/search.json?q=%23" + team1 + "&callback=?&geocode=53.779292%2C-1.579413%2C350mi";
var url2 = "http://search.twitter.com/search.json?q=%23" + team2 + "&callback=?&geocode=53.779292%2C-1.579413%2C350mi";
var geocoder = new google.maps.Geocoder();

function team1tweets() {
    $.getJSON(
    url1, function(results) { // get the tweets
        var res1 = results.results[0].text;
        var user1name = results.results[0].from_user;
        var user1Location = results.results[0].location;

        // get the first tweet in the response and place it inside the div
        $("#last-tweet1").html(res1 + "<p>from: " + user1name + " (" + user1Location + ")</p><p>");
        //convert location into longitude and latitude
        geocoder.geocode({
            address: user1Location
        }, function(locResult) {
            console.log(locResult);
            var lat1 = locResult[0].geometry.location.lat();
            var lng1 = locResult[0].geometry.location.lng();
            $("#testDiv").html("latitude:" + lat1 + "<p>longitude:" + lng1 + "</p>");
        });
    });
}

function team2tweets() {
    $.getJSON(
    url2, function(results) { // get the tweets
        var res2 = results.results[0].text;
        var user2name = results.results[0].from_user;
        var user2Location = results.results[0].location;
        $("#last-tweet2").html(res2 + "<p>from: " + user2name + " (" + user2Location + ")</p>"); // get the first tweet in the response and place it inside the div
        //convert location into longitude and latitude
        var convertLocUrl2 = "http://maps.googleapis.com/maps/api/geocode/json?address=" + user2Location + "&sensor=false&region=uk";
        geocoder.geocode({
            address: user2Location
        }, function(locResult) {
            var lat2 = locResult[0].geometry.location.lat();
            var lng2 = locResult[0].geometry.location.lng();
            $("#testDiv2").html("latitude:" + lat2 + "<p>longitude:" + lng2 + "</p>");
        });
    });
}

team1tweets();
team2tweets();

setInterval(checkStream1, 20000);
setInterval(checkStream2, 20000);

function checkStream1() {
    team1tweets();
}

function checkStream2() {
    team2tweets();
}